<template>
  <el-container class="layout-container">
    <el-aside :width="isCollapse ? '64px' : '220px'" class="aside-menu">
      <div class="logo">
        <img src="../assets/logo.png" alt="Logo" class="logo-img" />
        <h2 v-if="!isCollapse">高校教师绩效系统</h2>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        :collapse="isCollapse"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        router
        unique-opened
        @select="handleSelect"
      >
        <sidebar-item 
          v-for="route in permissionRoutes" 
          :key="route.path" 
          :item="route" 
          :base-path="''" 
        />
      </el-menu>
    </el-aside>
    
    <el-container>
      <el-header style="height: 60px;">
        <div class="header-left">
          <el-icon class="toggle-icon" @click="toggleSidebar">
            <Fold v-if="!isCollapse" />
            <Expand v-else />
          </el-icon>
          <breadcrumb />
        </div>
        
        <!-- 添加用户信息和下拉菜单 -->
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              <el-avatar :size="32" icon="UserFilled"></el-avatar>
              <span class="username">{{ userInfo.realName || '用户' }}</span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <el-main>
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Fold, Expand, ArrowDown } from '@element-plus/icons-vue'
import SidebarItem from '../components/SidebarItem.vue'
import Breadcrumb from '../components/Breadcrumb.vue'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const isCollapse = ref(false)

// 添加用户信息计算属性
const userInfo = computed(() => {
  return userStore.user || {}
})

// 计算当前活动菜单
// 计算当前活动菜单 - 修复选中状态问题
const activeMenu = computed(() => {
  // 如果是个人信息页面，返回上一个选中的菜单
  if (route.path === '/profile') {
    return localStorage.getItem('lastActiveMenu') || '/dashboard'
  }
  
  // 如果路由有指定的活动菜单，使用它
  if (route.meta && route.meta.activeMenu) {
    return route.meta.activeMenu
  }
  
  // 处理嵌套路由的情况
  if (route.matched && route.matched.length > 1) {
    // 对于嵌套路由，使用完整的当前路径
    return route.path
  }
  
  // 否则使用当前路径
  return route.path
})

// 处理菜单选择事件
const handleSelect = (index) => {
  // 如果当前不是在个人信息页面，保存选中的菜单
  if (route.path !== '/profile') {
    localStorage.setItem('lastActiveMenu', index)
  }
  
  // 如果点击的是当前路径，不做任何操作
  if (index === route.path) return
  
  // 导航到选中的路径，使用replace而不是push，避免历史记录堆积
  router.replace(index)
}

// 根据用户角色过滤路由
const permissionRoutes = computed(() => {
  const userRole = userStore.userRole || localStorage.getItem('userRole')
  return router.options.routes[0].children.filter(route => {
    if (route.meta?.hideInMenu) return false
    if (!route.meta || !route.meta.roles) return true
    return route.meta.roles.includes(userRole)
  })
})

// 在组件挂载时，如果没有保存的活动菜单，初始化为当前路径
onMounted(() => {
  if (!localStorage.getItem('lastActiveMenu')) {
    localStorage.setItem('lastActiveMenu', route.path)
  }
})

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'profile') {
    router.push('/profile')
  } else if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      userStore.logout()
      router.push('/login')
      ElMessage.success('已退出登录')
    }).catch(() => {})
  }
}
</script>

<style scoped>
/* 已有样式保持不变 */

/* 添加头部右侧用户信息样式 */
.header-right {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin: 0 8px;
  color: #333;
}

/* 保持侧边栏高度固定 */
.layout-container {
  height: 100vh;
}

.aside-menu {
  transition: width 0.3s;
  background-color: #304156;
  height: 100vh; /* 确保高度固定为100vh */
  overflow: hidden;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  background-color: #2b3649;
  overflow: hidden;
  white-space: nowrap;
  padding: 0 10px;
}

.logo-img {
  height: 32px;
  width: 32px;
  margin-right: 10px;
}

.logo h2 {
  margin: 0;
  font-size: 16px;
  white-space: nowrap;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 220px;
  min-height: calc(100vh - 60px);
}

.el-menu-vertical {
  border-right: none;
  height: calc(100vh - 60px); /* 确保菜单高度固定 */
}

.el-header {
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
}

.toggle-icon {
  font-size: 20px;
  cursor: pointer;
  margin-right: 20px;
}

.user-info {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from,
.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* 添加选中菜单项的样式 */
:deep(.el-menu-item.is-active) {
  background-color: #263445 !important;
  color: #409EFF !important;
  border-right: 3px solid #409EFF;
}

:deep(.el-sub-menu.is-active .el-sub-menu__title) {
  color: #409EFF !important;
}
</style>